package cn.calm.commons.interceptor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.osgi.OsgiHost;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import cn.calm.commons.provider.SessionProvider;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SesssionProviderInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
//		if (session.isNew()) {
			BundleContext context = (BundleContext) session.getServletContext()
					.getAttribute(OsgiHost.OSGI_BUNDLE_CONTEXT);
			if (context == null) {
				return invocation.invoke();
			}
			Collection<ServiceReference<SessionProvider>> serviceRefs = context
					.getServiceReferences(SessionProvider.class, null);
			if (serviceRefs == null) {
				return invocation.invoke();
			}
			List<SessionProvider> sessionProviders = new ArrayList<SessionProvider>();
			for (ServiceReference<SessionProvider> ref : serviceRefs) {
				sessionProviders.add(context.getService(ref));
			}
			for (SessionProvider sp : sessionProviders) {
				Map<String, Object> map = sp.provider();
				for (Entry<String, Object> ent : map.entrySet()) {
					session.setAttribute(ent.getKey(), ent.getValue());
				}
			}

//		}
		return invocation.invoke();
	}
}
